<template>
  <view class="listBoxa">
    <view class="answerList">
      <view class="answerCard" v-for="item in answerList" :key="item.id">
        <view class="cardContent">
          <view class="cardHeader">
            <view class="titleRow">
              <view class="title">{{ item.respondent_name }}</view>
            </view>
            <view class="metaInfo">
              <view class="description">{{ item.questionnaire_title }}</view>
              <view class="bottomRow">
                <view class="createTime">{{
                  formatDate(item.created_at)
                }}</view>
                <view class="answerCount">IP: {{ item.respondent_ip }}</view>
              </view>
            </view>
          </view>
          <view class="cardFooter">
            <view class="actionGroup">
              <view class="textBtn detailBtn" @click="viewAnswerDetail(item.id)">
                查看详情
              </view>
              <view class="textBtn exportBtn" @click="exportAnswer(item)">
                导出表格
              </view>
              <view class="moreActions" @click.stop="toggleMoreMenu(item.id)">
                <s-icon name="ellipsis" size="18" color="#909399" :style="{ transform: `rotate(90deg)` }" />
                <view class="moreMenu" v-if="showMoreMenu === item.id">
                  <view class="menuItem" @click.stop="deleteAnswer(item.id)">
                    删除记录
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="emptyTips" v-if="answerList.length === 0">
        <s-icon name="box" size="40" color="#ccc" />
        <view class="emptyText">暂无收集数据</view>
      </view>
    </view>
  </view>
  </template>
  <script>
    export default {
    props: {
      questionnaireId: {
        type: [String, Number],
        default: null,
      },
    },
    data() {
      return {
        answerList: [],
        loading: false,
        currentPage: 1,
        pageSize: 10,
        total: 0,
        showMoreMenu: null,
      };
    },
      created() {
      uni.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
      });

      this.loadAnswerList();
    },
    methods: {
      // 加载回答列表
      async loadAnswerList() {
        this.loading = true;
        try {
          const params = {
            page: this.currentPage,
            pageSize: this.pageSize,
          };

          if (this.questionnaireId) {
            params.questionnaire_id = this.questionnaireId;
          }

          const res = await this.sjuAjax.get("/answer/list", params);
          if (res && res.code === 200) {
            this.answerList = res.data.list;
            this.total = res.data.pagination.total;
          }
        } finally {
          this.loading = false;
        }
      },

      // 格式化日期
      formatDate(dateString) {
        if (!dateString) return "";
        const date = new Date(dateString);
        return `${date.getFullYear()}-${(date.getMonth() + 1)
          .toString()
          .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
      },

      // 查看回答详情
      viewAnswerDetail(answerId) {
        uni.navigateTo({
          url: `/pages/quest/answer?id=${answerId}`,
        });
      },

      // 切换更多菜单
      toggleMoreMenu(id) {
        this.showMoreMenu = this.showMoreMenu === id ? null : id;
      },

      // 删除回答记录
      deleteAnswer(id) {
        this.sjuAlert.showConfirm(
          "确定要删除该回答记录吗？\n删除后不可恢复！",
          async () => {
            try {
              await this.sjuAjax.post("/answer/delete", { id });
              uni.showToast({
                title: "删除成功",
                icon: "success",
              });
              this.loadAnswerList();
            } finally {
              this.showMoreMenu = null;
            }
          },
          () => {
            this.showMoreMenu = null;
          }
        );
      },

      // 导出文件并直接打开（简化版）
      async exportAnswer(item) {
        uni.showLoading({ title: "正在导出...", mask: true });
      
        try {
          // 1. 下载文件到临时路径
          const { tempFilePath } = await this.downloadFile(item.id);
        
          // 2. 直接打开文件（无需保存到永久目录）
          this.openTempFile(tempFilePath, `${item.questionnaire_title}-${item.respondent_name}.csv`);
        } catch (error) {
          console.error("导出失败:", error);
          this.showSaveError(error);
        } finally {
          uni.hideLoading();
        }
      },

      // 下载文件到临时目录
      downloadFile(id) {
        return new Promise((resolve, reject) => {
          uni.downloadFile({
            url: `https://ydd.yfyj.cc/api/answer/exportCSV?id=${id}`,
            success: (res) => {
              if (res.statusCode === 200) {
                resolve(res);
              } else {
                reject(new Error(`下载失败，状态码: ${res.statusCode}`));
              }
            },
            fail: (err) => reject(new Error(`下载请求失败: ${err.errMsg}`)),
          });
        });
      },

      // 打开临时文件
      openTempFile(tempFilePath, fileName) {
        uni.openDocument({
          filePath: tempFilePath,
          showMenu: true, // 显示右上角菜单（支持分享/保存）
          success: () => {
            uni.showToast({ title: "文件已打开", icon: "success" });
          },
          fail: (err) => {
            // 处理打开失败（如无默认应用）
            uni.showModal({
              title: "打开失败",
              content: "请安装支持的应用（如WPS）打开此文件",
              confirmText: "知道了",
              showCancel: false,
            });
          }
        });
      },

      // 错误提示
      showSaveError(error) {
        uni.showModal({
          title: "导出失败",
          content: error.message || "文件导出失败，请重试",
          showCancel: false,
        });
      }
    },
  };
  </script>
  <style lang="scss" scoped>
    /* 保持原有样式不变 */
    .listBoxa {
      margin-top: 20rpx;

      .answerList {
        .answerCard {
          margin-bottom: 20rpx;
          border-radius: 12rpx;
          background: #fff;
          box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

          .cardContent {
            .cardHeader {
              padding: 24rpx;

              .titleRow {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 16rpx;

                .title {
                  font-size: 34rpx;
                  font-weight: bold;
                  color: #333;
                  flex: 1;
                }
              }

              .metaInfo {
                display: flex;
                flex-direction: column;

                .description {
                  font-size: 28rpx;
                  color: #999;
                  margin-bottom: 16rpx;
                }

                .bottomRow {
                  display: flex;
                  justify-content: space-between;
                  align-items: center;

                  .createTime {
                    font-size: 26rpx;
                    color: #999;
                  }

                  .answerCount {
                    font-size: 26rpx;
                    color: #666;
                  }
                }
              }
            }

            .cardFooter {
              border-top: 1rpx solid #eee;

              .actionGroup {
                display: flex;
                justify-content: space-between;
                align-items: center;

                .textBtn {
                  font-size: 28rpx;
                  border-radius: 6rpx;
                  height: 84rpx;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  flex-grow: 1;
                  border-right: #eee 1px solid;

                  &.detailBtn {
                    color: #47c5c4;
                  }

                  &.exportBtn {
                    color: var(--v-theme);
                  }
                }

                .moreActions {
                  position: relative;
                  width: 84rpx;
                  display: flex;
                  justify-content: center;
                  align-items: center;

                  .moreMenu {
                    position: absolute;
                    right: 0;
                    top: 40rpx;
                    background: #fff;
                    border-radius: 8rpx;
                    box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
                    z-index: 10;
                    padding: 10rpx 0;
                    min-width: 180rpx;

                    .menuItem {
                      padding: 16rpx 24rpx;
                      font-size: 28rpx;
                      color: #666;

                      &:hover {
                        background: #f5f5f5;
                      }
                    }
                  }
                }
              }
            }
          }
        }

        .emptyTips {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 60rpx 0;
          color: #999;

          .emptyText {
            margin-top: 20rpx;
            font-size: 28rpx;
          }
        }
      }
    }
  </style>
